package com.atguigu.tingshu.album.testlock.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class TestServiceImpl implements  TestService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //setnx + 过期时间 + uuid + lua脚本
    public void testLock3() throws Exception{
        //获取当前锁  setIfAbsent == senx命令
        String uuid = UUID.randomUUID().toString();
        Boolean ifAbsent =
                stringRedisTemplate.opsForValue()
                        .setIfAbsent("lock",uuid,
                                3, TimeUnit.SECONDS);
        if(ifAbsent) { //获取锁成功
            try {
                //1 从redis获取数据
                //提前在redis手动添加初始值  set num  1
                String value = stringRedisTemplate.opsForValue().get("num");
                //2 判断非空
                if(StringUtils.isEmpty(value)) {
                    return;
                }
                //3 把redis获取数据+1
                //4 +1之后放回到redis里面
                int num = Integer.parseInt(value);
                stringRedisTemplate.opsForValue().set("num", String.valueOf(++num));

                //异常
            }finally {

                //lua脚本释放锁
                //创建对象
                DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
                //编写lua脚本
                String script = "if redis.call(\"get\",KEYS[1]) == ARGV[1]\n" +
                        "then\n" +
                        "    return redis.call(\"del\",KEYS[1])\n" +
                        "else\n" +
                        "    return 0\n" +
                        "end";
                //设置对象里面
                redisScript.setScriptText(script);
                //设置返回类型
                redisScript.setResultType(Long.class);
                //执行lua脚本
                stringRedisTemplate.execute(redisScript, Arrays.asList("lock"),uuid);
            }
        } else { //获取锁失败
            Thread.sleep(100);
            this.testLock2();
        }
    }


    //setnx实现分布式锁
    @Override
    public void testLock2() throws Exception{
        //获取当前锁  setIfAbsent == senx命令
        String uuid = UUID.randomUUID().toString();
        Boolean ifAbsent =
                stringRedisTemplate.opsForValue()
                        .setIfAbsent("lock",uuid,
                                3, TimeUnit.SECONDS);
        if(ifAbsent) { //获取锁成功
            try {
                //1 从redis获取数据
                //提前在redis手动添加初始值  set num  1
                String value = stringRedisTemplate.opsForValue().get("num");
                //2 判断非空
                if(StringUtils.isEmpty(value)) {
                    return;
                }
                //3 把redis获取数据+1
                //4 +1之后放回到redis里面
                int num = Integer.parseInt(value);
                stringRedisTemplate.opsForValue().set("num", String.valueOf(++num));

                //异常
            }finally {

                //释放锁
                //当前uuid 和 redis存储uuid是否相同
                String redis_uuid = stringRedisTemplate.opsForValue().get("lock");

                //index1  10s   index2
                if(uuid.equals(redis_uuid)) {
                    stringRedisTemplate.delete("lock");
                }

            }
        } else { //获取锁失败
            Thread.sleep(100);
            this.testLock2();
        }
    }

    //1 测试本地锁
    @Override
    public synchronized void testLock1() {
        //1 从redis获取数据
        //提前在redis手动添加初始值  set num  1
        String value = stringRedisTemplate.opsForValue().get("num");

        //2 判断非空
        if(StringUtils.isEmpty(value)) {
            return;
        }

        //3 把redis获取数据+1
        //4 +1之后放回到redis里面
        int num = Integer.parseInt(value);
        stringRedisTemplate.opsForValue().set("num", String.valueOf(++num));
    }

}
